{% extends 'base.html' %}
{% block styles %}
    {{ super() }}
    <!-- layui样式 -->
    <link rel="stylesheet" href="{{ url_for('static',filename='layui/css/layui.css') }}" media="all">
    <!-- 验证样式 -->
    <link rel="stylesheet" href="{{ url_for('static',filename='bootstrap_validator/bootstrap-validator.css') }}">
{% endblock %}
{% block content %}
    <div class="content-wrapper">
        <section class="content-header">
            <h1>
                IP地址管理
                <small>IP地址使用情况</small>
            </h1>
        </section>
        <section class="content">
            <div class="alert alert-info alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <h4><i class="icon fa fa-info"></i> 操作提示</h4>
                 1:表格行内进行编辑修改 2:'搜索'按钮没有内容就'重载'表格 3:增加IP会自动根据掩码计算增加
            </div>
            <div class="box">
                <div class="box-header">
                    <div class="row">
                        <div class="col-md-6">
                            <select id='select' class="select2" style="width: 25%;">
                                {% for i in ip %}
                                    <option>{{ i.name }}</option>
                                {% endfor %}
                            </select>
                            <div class="layui-inline">
                                <input class="layui-input" id="search_value">
                            </div>
                            <button class="layui-btn" id="reload">搜索</button>
                        </div>
                        <div class="col-md-6" style="text-align:right">
                            <button id="add_ip_address" class="btn btn-success">增加IP地址</button>
                            <button id="enabled" class="btn btn-success">可用/不可用</button>
                            <button id="delete" class="btn btn-danger"><i class="fa fa-trash-o"></i>&nbsp;删除</button>
                        </div>
                    </div>
                </div>
                <div class="box-body">
                    <table id="demo" lay-filter="test"></table>
                </div>
            </div>

            <!--弹出模态框-->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <div class="modal-title">
                                <span id="modal-title">根据IP掩码生成IP网络地址</span>
                            </div>
                        </div>
                        <div class="modal-body">
                            <form id="add_ip" class="form-horizontal">
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">
                                        <span>IP地址:</span>
                                    </label>
                                    <div class="col-sm-8">
                                        <input id="ip_address" name="ip_address" type="text" class="form-control">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">
                                        <span>子网掩码:</span>
                                    </label>
                                    <div class="col-sm-8">
                                        <input name="subnet_mask" type="text" class="form-control">
                                    </div>
                                </div>

                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">
                                关闭
                            </button>
                            <button type="submit" class="btn btn-primary" id="save">
                                提交
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
{% endblock content %}
{% block scripts %}
    {{ super() }}
    <script type="text/html" id="moban">
        {% raw %}
        {{#  if(d.enable == 0){ }}
        <span class="label label-success">可用</span>
        {{#  } else { }}
        <span class="label label-danger">不可用</span>
        {{#  } }}
        {% endraw %}
    </script>
    <!-- 验证样式validator的js -->
    <script src="{{ url_for('static',filename="bootstrap_validator/bootstrap-validator.js") }}"></script>
    <!-- layui的js -->
    <script src="{{ url_for('static',filename='layui/layui.all.js') }}"></script>
    <!-- select2的js -->
    <script src="{{ url_for('static',filename='bower_components/select2/dist/js/select2.full.min.js') }}"></script>
    <script>

        //验证表单
        $(function () {
            $("#add_ip").bootstrapValidator({
                message: '这个值是无效的',
                feedbackIcons: {
                    /*input状态样式图片*/
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    ip_address: {
                        message: 'IP验证失败',
                        validators: {
                            notEmpty: {
                                message: '地址不能为空'
                            },
                            ip: {
                                message: 'IP地址不合法'
                            }
                        }
                    },
                    subnet_mask: {
                        message: '子网掩码验证失败',
                        validators: {
                            notEmpty: {
                                message: '地址不能为空'
                            },
                            ip: {
                                message: 'IP地址不合法'
                            }
                        }
                    },
                }
            });
        });

        //重置模态框
        function clearModal() {
            $('#add_ip').data('bootstrapValidator').resetForm(true);
            document.getElementById("add_ip").reset();
        }

        //验证是否为IP
        function isValidIP(ip) {
            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            return reg.test(ip);
        }

        //初始化select2选项卡
        var select2 = $('.select2').select2({
            placeholder: '请选择类别',
            //allowClear: true
        })

        //select的内容
        var ip_select = $("#select").val();

        //初始化表单
        var table = layui.table;
        //方法级渲染
        table.render({
            elem: '#demo', //指定原始表格元素选择器（推荐id选择器）
            id: 'lzh', //设定容器唯
            height: 700, //设定容器高度
            skin: 'row', //列边框风格
            even: true, //开启隔行背景
            page: true, //开启分页
            limit: 25,
            limits: [10, 25, 50, 100],
            url: '{{ url_for('property.query_ip') }}',
            where: {select: ip_select,},
            //data: [{'id': 1, 'ip': '192.168.1.2', usable: 'True', hostname: '服务器A'}],
            //标题栏
            cols: [[
                {checkbox: true},
                {field: 'id', title: 'ID'},
                {field: 'ip', title: 'IP地址', sort: true, edit: 'text'},
                {field: 'mac', title: 'MAC地址', sort: true, edit: 'text'},
                {field: 'hostname', title: '主机名', edit: 'text'},
                {field: 'enable', title: '是否已用', sort: true, templet: '#moban'},
            ]],
        });

        //IP地址池分类
        $('#select').change(function () {
            var checkValue = $("#select").val();
            //console.log(checkValue)
            table.reload('lzh', {
                    where: {
                        select: checkValue,
                    }
                }
            )
        });


        //监听单元格编辑
        table.on('edit(test)', function (obj) {
            var value = obj.value //得到修改后的值
                , data = obj.data //得到所在行所有键值
                , field = obj.field; //得到修改字段
            // 获取修改的值
            function test() {
                var req = {id: data.id, field: field, value: value}
                return req
            }

            $.ajax({
                url: "{{ url_for('property.edit') }}",
                type: "POST",
                data: test(),
                success: function (rep) {
                    if (rep.status == 'success') {
                        layer.msg("修改成功");
                        table.reload('lzh');
                    }
                    else {
                        alert("后端返回错误！")
                    }
                },
                error: function () {
                    alert("出错！前端出错")
                }
            });
            //layer.msg('[ID: ' + data.id + '] ' + field + ' 字段更改为：' + value);
        });

        //可用按钮
        $('#enabled').on('click', function () {
            var checkStatus = table.checkStatus('lzh')
                , data = checkStatus.data;
            if (data.length == 0) {
                layer.msg("你需要选一点什么!")
            }
            else {
                var lists = new Array()
                for (var i = 0; i < data.length; i++) {
                    lists.push(data[i].id)
                }
                //console.log(lists)
                //layer.alert(JSON.stringify(data));
                $.ajax({
                    url: "{{ url_for('property.enable') }}",
                    type: "POST",
                    traditional: true, //取消深度序列化
                    data: {"id": lists},
                    success: function (rep) {
                        if (rep.status == 'success') {
                            layer.msg("提交成功");
                            table.reload('lzh');
                        }
                        else {
                            alert("后端返回错误！")
                        }
                    },
                    error: function () {
                        alert("出错！前端出错")
                    }
                });
            }
        });

        //搜索按钮
        $('#reload').on('click', function () {
            var search_value = $('#search_value')
            var checkValue = $("#select").val();
            //正则表达式判断是否唯为空
            var parten = /^\s*$/;
            if (parten.test(search_value.val())) {
                table.reload('lzh', {
                    where: {
                        select: checkValue
                    }
                })
                layer.msg("输入为空,重载表格")
            }
            else {
                table.reload('lzh', {
                        where: {
                            select: checkValue,
                            search: search_value.val()
                        }
                    }
                )
            }
        })

        //删除按钮
        $('#delete').on('click', function () {
            var checkStatus = table.checkStatus('lzh')
            var data = checkStatus.data;

            if (data.length == 0) {
                layer.msg("你需要选一点什么!")
            }
            else {
                layer.confirm('是否确定删除选中的内容?', {
                    btn: ['删除', '取消'] //方法按顺序回调
                    ,
                }, function () {
                    var lists = new Array()
                    for (var i = 0; i < data.length; i++) {
                        lists.push(data[i].id)
                    }
                    console.log(lists)
                    //layer.alert(JSON.stringify(data));
                    $.ajax({
                        url: "{{ url_for('property.delete') }}",
                        type: "POST",
                        traditional: true, //取消深度序列化
                        data: {"id": lists},
                        success: function (rep) {
                            if (rep.status == 'success') {
                                layer.msg("提交成功");
                                table.reload('lzh');
                            }
                            else {
                                alert("后端返回错误！")
                            }
                        },
                        error: function () {
                            alert("出错！前端出错")
                        }
                    });

                }, function () {
                });
            }
        });

        //增加IP按钮
        $('#add_ip_address').on('click', function () {
            clearModal()
            $("#myModal").modal("show");
        });

        //提交按钮
        $('#save').on('click', function () {
            //表单验证
            var bootstrapValidator = $('#add_ip').data('bootstrapValidator');
            bootstrapValidator.validate();
            // 拼接data内容增加,select的选项发送给ajax
            function data() {
                var data = $('#add_ip').serialize() + '&select=' + $("#select").val();
                return data
            }

            if (bootstrapValidator.isValid()) {
                $.ajax({
                    type: "POST",
                    url: "{{ url_for('property.add_ip') }}",
                    data: data(),
                    success: function (res) {
                        if (res.status == 'success') {
                            $('#myModal').modal('hide')
                            layer.msg("提交成功");
                            table.reload('lzh');
                        }
                        else {
                            layer.alert('后端抛出异常:'+res.message);
                        }
                    },
                    error: function () {
                        alert("前端出错,无法提交请求到后端")
                    }
                });
            }
            else {
                layer.msg("表单验证失败！");
            }
        });


    </script>

{% endblock scripts %}